import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/live/live_detail_entity.dart';
import 'package:sports_new/entity/match/expert_views_entity.dart';
import 'package:sports_new/entity/live/live_plan_entity.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/view/expert/items/plan_item.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/header_delegate.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../../resources/colours.dart';
import '../../../resources/styles.dart';
import '../../../server/api/expert_api.dart';
import '../../../utils/utils.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/gif.dart';
import '../../expert/items/plan_list_item.dart';
import '../../pick/items/expert_record_tag.dart';

class LivePlanView extends StatefulWidget {
  const LivePlanView({super.key, required this.info, required this.sportsId});

  final LiveDetailEntity? info;
  final int sportsId;

  @override
  State<LivePlanView> createState() => _LivePlanViewState();
}

class _LivePlanViewState extends State<LivePlanView> {
  List<PlanEntity>? livePlan;
  List<List<PlanEntity>>? otherPlan;
  LiveDetailEntity? get data => widget.info;
  int get sportsId => widget.sportsId;
  int _page = 1;
  int pageSize = 15;
  EasyRefreshController refreshController = EasyRefreshController(controlFinishLoad: true);

  int get page => _page;

  set page(int value) => setState(() => _page = value);

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async{
    LivePlanEntity entity = await ExpertApi.getLivePlan(
        "${data?.matchId}",
        data?.expertId,
        sportsId,
        page,
        pageSize
    );
    livePlan = entity.recommend;
    List<PlanEntity>? list = entity.other;
    otherPlan = formList(list);
    setState(() {});
  }

  Future loadMore() async{
    page += 1;
    List<PlanEntity>? result = await ExpertApi.getLivePlanOther(
        "${data?.matchId}",
        data?.expertId,
        sportsId,
        page,
        pageSize
    );
    otherPlan?.addAll(formList(result));
    refreshController.finishLoad(
      (otherPlan?.length ?? 0) < page*pageSize || result.noValue?
      IndicatorResult.noMore:IndicatorResult.success
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheet(
      onClosing: (){},
      backgroundColor: Colours.greyF2F3F7,
      constraints: BoxConstraints(
        maxHeight: Get.height - 199 - MediaQuery.of(context).padding.top,
      ),
      builder: (BuildContext context) => LoadingWidget(
        isLoading: livePlan == null && otherPlan == null,
        data: livePlan?.length == 0 && otherPlan?.length == 0,
        child: () => Stack(
          children: [
            EasyRefresh.builder(
              footer: Styles.refreshFooter(position: IndicatorPosition.locator),
              controller: refreshController,
              onLoad: loadMore,
              childBuilder: (context, physics) => CustomScrollView(
                physics: physics,
                slivers: [
                  if(livePlan.hasValue)
                  SliverMainAxisGroup(
                    slivers: [
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: HeaderDelegate(
                          child: Container(
                            color: Colours.greyF2F3F7,
                            padding: const EdgeInsets.all(12),
                            child: QkdText("专家在售方案",
                              fontSize: 16,
                              fontWeight: FontWeight.w500
                            ),
                          ),
                          extent: 46
                        )
                      ),
                      SliverList.list(
                        children: livePlan?.map<Widget>((e) => Block(
                          cardStyle: const CardStyle(
                            padding: EdgeInsets.symmetric(horizontal: 12),
                            margin: EdgeInsets.symmetric(horizontal: 8)
                          ),
                          child: PlanItem(
                            liveJump: false,
                            entity: e,
                            eventType: 'liveroom_plan_view',
                            jumpParam: {"roomId": "${data?.liveId}"},
                          )
                        )).toList().insertEvery(
                          Container(height: 8)
                        ) ?? [],
                      )
                    ]
                  ),
                  if(otherPlan.hasValue)
                  SliverMainAxisGroup(
                    slivers: [
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: HeaderDelegate(
                          child: Container(
                            color: Colours.greyF2F3F7,
                            padding: const EdgeInsets.all(12),
                            child: const QkdText(
                              "更多热门方案",
                              fontSize: 16,
                              fontWeight: FontWeight.w500
                            )
                          ),
                          extent: 46
                        )
                      ),
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          childCount: otherPlan?.length ?? 0,
                            (context, p) => Block(
                            cardStyle: const CardStyle(
                              padding: EdgeInsets.symmetric(horizontal: 12),
                              margin: EdgeInsets.fromLTRB(8, 0, 8, 8)
                            ),
                            child: PlanListItem(
                              planList: otherPlan![p],
                              eventType: 'liveroom_plan_view',
                              jumpParam: {"roomId": "${data?.liveId}"},
                            )
                          )
                        )
                      )
                    ]
                  ),
                  const FooterLocator.sliver()
                ],
              ),
            ),
            Positioned(
              right: 0,
              child: GestureDetector(
                onTap: () {
                  Get.back();
                },
                child: Container(
                  padding: const EdgeInsets.all(12),
                  child: Image.asset(
                    Utils.getImgPath('close.png'),
                    width: 24, height: 24,color: Colours.grey66,
                  ),
                ),
              )
            )
          ],
        ),
      )
    );
  }

  Widget planInfoWidget(PlanEntity? entity) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GestureDetector(
          onTap: () => Get.toNamed(Routes.userPage,arguments: entity?.expertId,parameters: {"type":"2"}),
          child: Row(
            children: [
              Stack(
                alignment: AlignmentDirectional.center,
                clipBehavior: Clip.none,
                children: [
                  const Positioned(
                    left: -7,
                    child: GifWidget(
                        width: 54,height: 54,
                        asset: "expert_live.gif",
                        duration: Duration(milliseconds: 500)
                    ),
                  ),
                  Container(
                    width: 40,
                    height: 40,
                    clipBehavior: Clip.antiAlias,
                    decoration: BoxDecoration(
                        border: Border.all(
                            color: Colours.greyEE,
                            width: 0.5,
                            strokeAlign: BorderSide.strokeAlignOutside
                        ),
                        shape: BoxShape.circle
                    ),
                    child: CachedNetworkImage(
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Container(),
                        errorWidget: (context, url, error) => Container(),
                        imageUrl: entity?.expertLogo ?? ''
                    ),
                  ),
                ],
              ),
              Container(width: 7),
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  QkdText(entity?.expertName ?? '',
                    fontWeight: FontWeight.w500,fontSize: 16
                  ),
                  Container(height: 2),
                  Row(
                    children: [
                      ExpertRecordTag(type: 4, text: entity?.firstTag),
                      Container(width: 6),
                      ExpertRecordTag(type: 5, text: entity?.secondTag)
                    ],
                  )
                ],
              ),
              const Spacer(),
              FocusButton(
                entity?.isFocus ?? 0,
                expertId: entity?.expertId,
                width: 80,height: 30,
                onTap: (value) {
                  entity?.isFocus = value;
                }
              )
            ],
          ),
        ),
        Container(height: 12),
        if(entity?.expertInfo.hasValue == true)...[
          QkdText("专家简介：${(entity?.expertInfo ?? "").split("").map(
                  (e) => RegExp(r'[\u4E00-\u9FA5]').hasMatch(e)?"$e\u200A":e
          ).join()}",
            maxLines: 2,
            fontSize: 12,color: Colours.grey66
          ),
          Container(height: 16),
          const Divider(height: 0.5,color: Colours.greyEE).paddingSymmetric(horizontal: 12)
        ],
        Container(height: 12),
      ],
    );
  }

  List<List<PlanEntity>> formList(List<PlanEntity>? entity) {
    List<List<PlanEntity>> list = [];
    if (entity?.isEmpty == true || entity?.length == null) {
      return [];
    }
    List<int> spot = [];
    var sportsId = entity![0].sportsId;
    var expertId = entity[0].expertId;
    for (var i = 0; i < entity.length; i++) {
      if (entity[i].sportsId != sportsId ||
          entity[i].expertId != expertId) {
        spot.add(i);
        sportsId = entity[i].sportsId;
        expertId = entity[i].expertId;
      }
      ;
    }
    if (spot.length > 1) {
      list.add(entity.sublist(0, spot[0]));
      list.addAll(List.generate(spot.length, (index) {
        if (index == spot.length - 1) return entity.sublist(spot.last, entity.length);
        return entity.sublist(spot[index], spot[index + 1]);
      }));
    } else if (spot.length == 1) {
      list.add(entity.sublist(0, spot[0]));
      list.add(entity.sublist(spot[0], entity.length));
    } else {
      list.add(entity);
    }
    return list;
  }
}
